package com.example.turingim.handler;

import com.alibaba.fastjson.JSON;
import com.example.turingim.IMServer;
import com.example.turingim.common.MessageType;
import com.example.turingim.common.ResponseResult;
import com.example.turingim.dto.ChatMessage;

import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.internal.StringUtil;

public class ChatHandler {
    public static void execute(ChannelHandlerContext ctx, TextWebSocketFrame frame) {
        try {
            ChatMessage chat = JSON.parseObject(frame.text(), ChatMessage.class);
            switch (MessageType.match(chat.getType())) {
                case PRIVATE:
                    {
                        if (StringUtil.isNullOrEmpty(chat.getTarget())) {
                            ctx.channel().writeAndFlush(ResponseResult.fail("消息发送失败，发送消息请指定接收对象"));
                            return;
                        }
                        Channel channel = IMServer.USERS.get(chat.getTarget());
                        if (channel == null || !channel.isActive()) {
                            ctx.channel()
                                    .writeAndFlush(
                                            ResponseResult.fail(
                                                    "消息发送失败，对方" + chat.getTarget() + "不在线"));
                        } else {
                            channel.writeAndFlush(
                                    ResponseResult.success(
                                            "私聊消息（"
                                                    + chat.getNickname()
                                                    + "）"
                                                    + chat.getContent()));
                        }
                    }
                    ;
                case GROUP:
                    IMServer.GROUP.writeAndFlush(
                            ResponseResult.success(
                                    "群消息（" + chat.getNickname() + "）" + chat.getContent()));
                default:
                    ctx.channel().writeAndFlush(ResponseResult.fail("不支持的消息类型"));
            }
        } catch (Exception e) {
            ctx.channel().writeAndFlush(ResponseResult.fail("发送消息格式错误，请确认后再试"));
        }
    }
}
